package com.droid.library.widget.recyclerview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Decoration
 *
 * @author wangheng
 */
public class DividerDecoration extends RecyclerView.ItemDecoration {

    private Drawable mDivider;
    private int dividerSize;


    public DividerDecoration(Context context,@ColorInt int dividerColor, int dividerSize) {
        this.dividerSize = dividerSize;
        mDivider = new ColorDrawable(dividerColor);
    }


    @Override
    public void onDraw(Canvas c, RecyclerView parent) {

        drawVertical(c, parent);

    }

    public void drawVertical(Canvas c, RecyclerView parent) {
        int footerCount = 0;
        int headerCount = 0;
        RecyclerView.Adapter adapter = parent.getAdapter();
        int count = adapter.getItemCount();
        if(adapter instanceof BaseRecyclerAdapter){
            BaseRecyclerAdapter ada = ((BaseRecyclerAdapter)parent.getAdapter());
            footerCount = ada.getFootersCount();
            headerCount = ada.getHeadersCount();
        }

        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);

            int itemPosition = parent.getChildAdapterPosition(child);
            if(itemPosition < headerCount){
                continue;
            }else if(itemPosition > count - footerCount - 1){
                continue;
            }

            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + dividerSize;
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {

        int footerCount = 0;
        int headerCount = 0;
        RecyclerView.Adapter adapter = parent.getAdapter();
        if(adapter instanceof BaseRecyclerAdapter){
            BaseRecyclerAdapter ada = ((BaseRecyclerAdapter)parent.getAdapter());
            footerCount = ada.getFootersCount();
            headerCount = ada.getHeadersCount();
        }

        if(itemPosition < headerCount){
            outRect.set(0,0,0,0);
        }else if(itemPosition > adapter.getItemCount() - footerCount - 1){
            outRect.set(0,0,0,0);
        }else {
            outRect.set(0, 0, 0, dividerSize);
        }
    }
}